//
//  ELCAssetTablePicker.m
//
//  Created by ELC on 2/15/11.
//  Copyright 2011 ELC Technologies. All rights reserved.
//

#import "ELCAssetTablePicker.h"
#import "ELCAssetCell.h"
#import "ELCAsset.h"
#import "ELCAlbumPickerController.h"

@interface ELCAssetTablePicker ()

@property (nonatomic, assign) int columns;
@property (nonatomic, weak) NSString *barTitle;
@end

@implementation ELCAssetTablePicker

//Using auto synthesizers
UIButton *doneButton;
int picCount;

- (id)initWithTitle:(NSString *)barNameTitle
{
    self = [super init];
    if (self) {
        //Sets a reasonable default bigger then 0 for columns
        //So that we don't have a divide by 0 scenario
        self.columns = 4;
        //获得顶部title
        _barTitle = barNameTitle;
    }
    return self;
}

-(void)back
{ 
    [doneButton setTitle:[NSString stringWithFormat:@"确定(%d/%d)",picCount,self.maxPicNum] forState:UIControlStateNormal];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
	[self.tableView setAllowsSelection:NO];

    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    self.elcAssets = tempArray;
	
    if (self.immediateReturn) {
        
    } else {
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        backButton.titleLabel.font = [UIFont systemFontOfSize:14.0f]; 
        backButton.frame = CGRectMake(7, 0.0, 40, 40);
//        [backButton setImage:[UIImage imageNamed:@"addressBack.png"] forState:UIControlStateNormal];
        [backButton setTitle:@"返回" forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
        temporaryBarButtonItem.style = UIBarButtonItemStylePlain;
        [self.navigationItem setLeftBarButtonItem:temporaryBarButtonItem];
        
        doneButton=[UIButton buttonWithType:UIButtonTypeCustom];
        doneButton.frame=CGRectMake(246, 6, 67, 29);
        [doneButton addTarget:self action:@selector(doneAction:) forControlEvents:(UIControlEventTouchUpInside)];
     
        doneButton.titleLabel.font = [UIFont systemFontOfSize: 14.0];
        doneButton.titleLabel.text = @"确定";
//        [doneButton setBackgroundImage:[UIImage imageNamed:@"savePicBtn.png"] forState:UIControlStateNormal];
        
//        [doneButton setBackgroundImage:[UIImage imageNamed:@"savePicBtnClick.png"] forState:UIControlStateHighlighted];
        
        UIBarButtonItem *doneButtonItem = [[UIBarButtonItem alloc] initWithCustomView:doneButton];
        doneButtonItem.style = UIBarButtonItemStylePlain;
        
        [self.navigationItem setRightBarButtonItem:doneButtonItem];
        UILabel *chuliLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 30)];
        chuliLabel.text = @"处理中...";
        chuliLabel.textColor = [UIColor whiteColor];
        chuliLabel.textAlignment = NSTextAlignmentCenter;
        chuliLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
        self.navigationItem.titleView = chuliLabel;
//        [self.navigationItem setTitle:@"处理中..."];
    }
	[self performSelectorInBackground:@selector(preparePhotos) withObject:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.columns = self.view.bounds.size.width / 80;
    picCount = 0;
    [doneButton setTitle:[NSString stringWithFormat:@"确定(0/%d)",self.maxPicNum] forState:UIControlStateNormal];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    self.columns = self.view.bounds.size.width / 80;
    [self.tableView reloadData];
}

- (void)preparePhotos
{
    //顶部title自定义
    [self.tableView reloadData];
    UILabel *zhaoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 30)];
    zhaoLabel.text = _barTitle;
    zhaoLabel.textColor = [UIColor whiteColor];
	zhaoLabel.textAlignment = NSTextAlignmentCenter;
    zhaoLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    self.navigationItem.titleView = zhaoLabel;
    
    @autoreleasepool {

        [self.assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) { 
            if (result == nil) {
                return;
            }
            
            NSString *sGroupPropertyName = (NSString *)[self.assetGroup valueForProperty:ALAssetsGroupPropertyName];
            [self.navigationItem setTitle:sGroupPropertyName];
            
            ELCAsset *elcAsset = [[ELCAsset alloc] initWithAsset:result];
            [elcAsset setParent:self];
            
            BOOL isAssetFiltered = NO;
            if (self.assetPickerFilterDelegate &&
               [self.assetPickerFilterDelegate respondsToSelector:@selector(assetTablePicker:isAssetFilteredOut:)])
            {
                isAssetFiltered = [self.assetPickerFilterDelegate assetTablePicker:self isAssetFilteredOut:(ELCAsset*)elcAsset];
            }

            if (!isAssetFiltered) {
                [self.elcAssets addObject:elcAsset];
            }

         }];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            // scroll to bottom
            long section = [self numberOfSectionsInTableView:self.tableView] - 1;
            long row = [self tableView:self.tableView numberOfRowsInSection:section] - 1;
            if (section >= 0 && row >= 0) {
                NSIndexPath *ip = [NSIndexPath indexPathForRow:row
                                                     inSection:section];
                        [self.tableView scrollToRowAtIndexPath:ip
                                              atScrollPosition:UITableViewScrollPositionBottom
                                                      animated:NO];
            }
        });
    }
}

- (void)doneAction:(id)sender
{	
	NSMutableArray *selectedAssetsImages = [[NSMutableArray alloc] init];

	for (ELCAsset *elcAsset in self.elcAssets) {
		if ([elcAsset selected]) {
			[selectedAssetsImages addObject:[elcAsset asset]];
		}
	}
    [self.parent selectedAssets:selectedAssetsImages];
}

- (BOOL)shouldSelectAsset:(ELCAsset *)asset
{ 
    NSUInteger selectionCount = 0;
    for (ELCAsset *elcAsset in self.elcAssets) {
        if (elcAsset.selected) selectionCount++;
    }
    BOOL shouldSelect = YES;
    if ([self.parent respondsToSelector:@selector(shouldSelectAsset:previousCount:)]) {
        shouldSelect = [self.parent shouldSelectAsset:asset previousCount:selectionCount];
    }
    
    if(shouldSelect)
    {
        ++picCount;
        
        [doneButton setTitle:[NSString stringWithFormat:@"确定(%d/%d)",picCount,self.maxPicNum] forState:UIControlStateNormal];
    }
    return shouldSelect;
}

- (void)assetSelected:(ELCAsset *)asset
{      
    if (self.singleSelection) {

        for (ELCAsset *elcAsset in self.elcAssets) {
            if (asset != elcAsset) { 
                elcAsset.selected = NO;
            } 
        }
    }
    if (self.immediateReturn) {
        NSArray *singleAssetArray = @[asset.asset];
        [(NSObject *)self.parent performSelector:@selector(selectedAssets:) withObject:singleAssetArray afterDelay:0];
    }
}

-(void)cancelPic
{
    --picCount;
    
    [doneButton setTitle:[NSString stringWithFormat:@"确定(%d/3)",picCount] forState:UIControlStateNormal];
}

#pragma mark UITableViewDataSource Delegate Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.columns <= 0) { //Sometimes called before we know how many columns we have
        self.columns = 4;
    }
    NSInteger numRows = ceil([self.elcAssets count] / (float)self.columns);
    return numRows;
}

- (NSArray *)assetsForIndexPath:(NSIndexPath *)path
{
    long index = path.row * self.columns;
    long length = MIN(self.columns, [self.elcAssets count] - index);
    return [self.elcAssets subarrayWithRange:NSMakeRange(index, length)];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"Cell";
        
    ELCAssetCell *cell = (ELCAssetCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {		        
        cell = [[ELCAssetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    [cell setAssets:[self assetsForIndexPath:indexPath]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 79;
}

- (int)totalSelectedAssets
{
    int count = 0;
    
    for (ELCAsset *asset in self.elcAssets) {
		if (asset.selected) {
            count++;	
		}
	}
    
    return count;
}


@end
